const FILE_BASE_NAME = 'tmp_base64src'

/*
* 将base64图片转化为url 提供给wx.getImageInfo使用
* */
export const base64ToSrc = function (base64data) {
  return new Promise((resolve, reject) => {
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []
    if (!format) {
      reject(new Error('ERROR_BASE64SRC_PARSE'))
    }
    const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`
    const buffer = uni.base64ToArrayBuffer(bodyData)
    const fsm = uni.getFileSystemManager()
    fsm.writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success() {
        resolve(filePath)
      },
      fail(e) {
        console.log(`e`, e)
        reject(new Error('ERROR_BASE64SRC_WRITE'))
      },
    })
  })
}

/*
* 将buffer图片转化为url 提供给wx.getImageInfo使用
* */
export const bufferToSrc = function (buffer) {
  return new Promise((resolve, reject) => {
    const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.png`
    const fsm = uni.getFileSystemManager()
    fsm.writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success() {
        resolve(filePath)
      },
      fail() {
        reject(new Error('ERROR_BASE64SRC_WRITE'))
      },
    })
  })
}

/*
* 获取远程图片的信息
* */
export function getImageInfo(url) {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: url,
      success: (res) => {
        console.log(`res`, res)
        resolve(res)
      },
      fail: (err) => {
        console.log(`err`, err)
        resolve('')
      },
    })
  })
}

/**
 *
 * @param ctx 画布content
 * @param info 相关信息
 * @param that 页面组件本身
 * @returns {Promise<void>}
 */
export async function draw(ctx, info, that) {
  // 白色背景
  ctx.setFillStyle('white')
  ctx.fillRect(0, 0, 310, 450)
  ctx.draw()

  uni.showLoading()
  let imageInfo = await getImageInfo(info.bg)
  uni.hideLoading()
  ctx.drawImage(imageInfo, 0, 0, 275, 400)

  let url = await bufferToSrc(info.imgBuffer)
  imageInfo = await getImageInfo(url)
  ctx.drawImage(imageInfo, 170, 310, 75, 85)
  ctx.draw(true)
}

/**
 * 将canvas保存至本地
 * @param config 配置信息 {canvasId,}
 * @param that
 * @returns {Promise<void>}
 */
export async function canvasSave(config, that) {
  uni.canvasToTempFilePath({
    canvasId: config.canvasId,
    success: (res) => {
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: function (res) {
          uni.showToast({
            title: '分享图片已保存到相册,请到朋友圈选择图片发布',
          })
        },
      })
    },
    fail: (err) => {
      console.log(`fail`, err)
    },
  }, that)
}

/**
 * 获取图片
 * @param url
 * @param canvas
 * @returns {Promise<unknown>}
 *
 let imgBg = await this.imageGet('https://656e-env-1gtfew9ga2e803fd-1308727414.tcb.qcloud.la/bg/icon_invite_out_01.png', canvas)
 ctx.drawImage(imgBg, 0, 0, imgBg.width, imgBg.height, 0, 0, canvas.width, canvas.height)
 */
export async function imageLoad(url, canvas){
  return new Promise((resolve, reject) => {
    let img
    // #ifdef MP-WEIXIN
    img = canvas.createImage()
    // #endif
    // #ifdef H5
    img = new Image()
    img.setAttribute('crossOrigin', 'anonymous') // 小程序运行报错
    // img.crossOrigin = 'anonymous'
    // #endif
    img.src = url
    img.onload = () => {
      resolve(img)
    }
    img.onerror = (e) => {
      console.error(`imageLoad`, e)
      reject(e)
    }
  })
}
